window.addEventListener('load', function() {
    //获取元素
    let caseSidebar = getEle('#caseSidebar');
    let main = getEle('main');
    //金融案例模块
    let financialCase = getEle('#financial-case');
    //企业案例
    let businessCase = getEle('#business-case');
    // 政务案例
    let governmentCase = getEle('#government-case');
    //更多伙伴
    let morePartners = getEle('#more-partners');
    // 侧边栏对应的模块
    let spans = getEleAll('#caseSidebar span');
    //定义 每个模块距离最上方的距离
    let mainTop = main.offsetTop;
    let financialCaseTop = mainTop + financialCase.offsetTop;
    let businessCaseTop = mainTop + businessCase.offsetTop;
    let governmentCaseTop = mainTop + governmentCase.offsetTop;
    let morePartnersTop = mainTop + morePartners.offsetTop;
    window.addEventListener('scroll', function() {
        let wPage = window.pageYOffset;
        //  需求1: 根据滚动的距离将侧边栏设置为固定还是相对定位
        if (wPage >= mainTop) {
            caseSidebar.style.position = 'fixed';
            // 需求2: 根据滚动的距离判定当前属于哪个模块并且 给侧边栏设置相应的 class
            setSpanClass(wPage);
        } else {
            caseSidebar.style.position = 'absolute';
            clearSpanClass(spans);
            spans[0].className = 'selected';
        }
    });
    // 设置类
    function setSpanClass(wPage) {
        wPage = Math.ceil(wPage);
        if (financialCaseTop <= wPage && wPage < businessCaseTop) {
            clearSpanClass(spans);
            spans[0].className = 'selected';
        } else if (wPage < governmentCaseTop) {
            clearSpanClass(spans);
            spans[1].className = 'selected';
        } else if (wPage < morePartnersTop) {
            clearSpanClass(spans);
            spans[2].className = 'selected';
        } else {
            clearSpanClass(spans);
            spans[3].className = 'selected';
        }
    }
    // 清除类
    function clearSpanClass(dom) {
        for (let i = 0; i < dom.length; i++) {
            dom[i].className = '';
        }
    }
    // 给侧边栏帮点点击事件
    caseSidebar.addEventListener('click', function(e) {
        getSkip(e.target);
    });

    function getSkip(node) {
        let nodeIndex = node.getAttribute('data-index');
        let htmlNode = document.documentElement;
        if (nodeIndex) {
            let dom = getEle(`div[data-index='${nodeIndex}']`);
            let motionY = dom.offsetTop + mainTop;
            animate(htmlNode, motionY);
        }
    }
    // 动画函数
    function animate(obj, target, callback) {
        // 先清除以前的定时器，只保留当前的一个定时器执行
        clearInterval(obj.timer);
        obj.timer = setInterval(() => {
            let step = (target - document.documentElement.scrollTop) / 10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            if (Math.ceil(document.documentElement.scrollTop) == target) {
                clearInterval(obj.timer);
                callback && callback();
            }
            document.documentElement.scrollTop = document.documentElement.scrollTop + step;
        }, 15);
    }
});